package com.dw.utils;


import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

/**
 * 连接工具
 * @author wangxingchao
 *
 */
public class HibernateSessionFactory {
	private static Configuration configuration = null;
	private static SessionFactory sessionFactory = null;
	private static ServiceRegistry serviceRegistry = null;
	
	
	static {
		try {
			// 首先获取配置信息
			configuration =  new Configuration().configure("hibernate.cfg.xml");//读取hibernate-cfg.xml,如没有会报错
			serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
			
			// 创建Session Factory			
			sessionFactory = configuration.buildSessionFactory(serviceRegistry);
		} catch (HibernateException e) {
			// System.out.println("SessionFactory创建失败");
			e.printStackTrace();
		}
	}
	
	/**获得Session **/
	public static Session getSession() {
		Session session = null;
		if(null==session || false==session.isOpen()){
			session = sessionFactory.openSession();
		}
		
		return session;
	}
	/**关闭Session**/
	public static void closeSession(Session session){
		try {
			if(null!=session && session.isOpen())
				session.close();
		} catch (HibernateException e) {
			e.printStackTrace();
		}
	}
}